<?php
namespace app\store\controller\food\goods;

use app\store\controller\food\Controller;
use app\store\model\Category as CategoryModel;
use app\store\model\Shop as ShopModel;
use think\facade\View;

/**
 * 商品分类
 */
class Category extends Controller
{
	/**
	 * 门店选择
	 */
	public function opt()
	{
		if(!$this->is_admin OR $this->shop_mode == 10){
			return redirect(url('food.goods.category/index',['shop_id' => $this->shop_id]));
		}
	    $model = new ShopModel;
        $shoplist = $model->getList(false);
	    return View::fetch('opt', compact('shoplist'));
	}
    /**
     * 分类列表
     */
    public function index($shop_id)
    {
		$shop = ShopModel::detail($shop_id);
		$shop_name = $shop['shop_name'];
        $model = new CategoryModel;
        $list = $model->getCacheTree($shop_id);
        return View::fetch('index', compact('list','shop_name','shop_id'));
    }

    /**
     * 删除分类
     */
    public function delete($id)
    {
        $model = CategoryModel::get($id);
        if (!$model->remove()) {
            $error = $model->getError() ?: '删除失败';
            return $this->renderError($error);
        }
        return $this->renderSuccess('删除成功');
    }

    /**
     * 添加分类
     */
    public function add($shop_id)
    {
        $model = new CategoryModel;
        if (!$this->request->isAjax()) {
            $list = $model->getCacheTree($shop_id);
            return View::fetch('add', compact('list'));
        }
        // 新增记录
        if ($model->add($this->postData('data'),$shop_id)) {
            return $this->renderSuccess('添加成功', url('food.goods.category/index',['shop_id' => $shop_id]));
        }
        $error = $model->getError() ?: '添加失败';
        return $this->renderError($error);
    }

    /**
     * 编辑
     */
    public function edit($id, $shop_id)
    {
        // 模板详情
        $model = CategoryModel::get($id, ['image']);
        if (!$this->request->isAjax()) {
            // 获取所有地区
            $list = $model->getCacheTree($shop_id);
            return View::fetch('edit', compact('model', 'list'));
        }
        // 更新记录
        if ($model->edit($this->postData('data'),$shop_id)) {
            return $this->renderSuccess('更新成功', url('food.goods.category/index',['shop_id' => $shop_id]));
        }
        $error = $model->getError() ?: '更新失败';
        return $this->renderError($error);
    }

}
